package com.yq.spring.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yq.spring.dao.UserMapper;

@Controller
public class HelloController {
	// 设置好账号的ACCESS_KEY和SECRET_KEY
	public static final String ACCESS_KEY = "";
	public static final String SECRET_KEY = "";
	// 需要上传的空间名
	public static final String BUCKET_NAME = "";

	@Autowired
	private UserMapper userMapper;

	@RequestMapping(value="/hello")

	public String index(Model model){
		
		model.addAttribute("hello", userMapper.selectByPrimaryKey("123"));
		return "index";
		
	}

	@RequestMapping(value="/imgUpload",method=RequestMethod.POST)
	public String imageUpload(@RequestParam("uploadFile") MultipartFile[] files,
			HttpServletRequest request,
			Model model) throws IOException{
		if(files.length>0 && files!=null){
			//循环数组中的图片文件
			List<String> list = new ArrayList<>();
			 for(int i = 0;i<files.length;i++){  
	                MultipartFile file = files[i];  
	                list.add(imagesUpload(file));
	            }  
			 //对数组中的内容进行判断
			 if(list!=null||!list.isEmpty()){
				 model.addAttribute("imgs", list);
			 }
		}
		return "index";
}
	/**
	 * 对图片输入流进行byte转换
	 * @param uploadBytes
	 * @return
	 * @throws IOException
	 */
	private byte[] toByteArray(InputStream uploadBytes) throws IOException {
		 ByteArrayOutputStream out=new ByteArrayOutputStream();
	        byte[] buffer=new byte[1024*4];
	        int n=0;
	        while ( (n=uploadBytes.read(buffer)) !=-1) {
	            out.write(buffer,0,n);
	        }
	        return out.toByteArray();
	}
	
	private String imagesUpload(MultipartFile file) throws IOException{

		//构造一个带指定Zone对象的配置类,官方文档中写的是zone0，但是运行起来会会返回异常，
		//所以改成  华北	Zone.zone1()
		Configuration cfg = new Configuration(Zone.zone1());
		UploadManager uploadManager = new UploadManager(cfg);
		//默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = file.getOriginalFilename();
		//图片地址
		String DownloadUrl =null;
		try {
			//获取文件流
		    InputStream uploadBytes = file.getInputStream();
		    //调用toByteArray将其转换成
		    byte[] data=toByteArray(uploadBytes);
		    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		    String upToken = auth.uploadToken(BUCKET_NAME);
		    try {
		        Response response = uploadManager.put(data,key,upToken,null, null, true);
		        //解析上传成功的结果
		        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		         DownloadUrl = "你的域名"+key+"?图片样式(如果不加去掉?)";
		    } catch (QiniuException ex) {
		        Response r = ex.response;
		        System.err.println(r.toString());
		        try {
		            System.err.println(r.bodyString());
		        } catch (QiniuException ex2) {
		            //ignore
		        }
		    }
		} catch (UnsupportedEncodingException ex) {
		    //ignore
		}
		return DownloadUrl;
		
	}
	
}
